<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="18">
            <a-col :md="6" :sm="24">
              <a-form-item label="用户名">
                <a-input placeholder="请输入用户名" v-model="queryParam.username"/>
              </a-form-item>
            </a-col>

            <!-- <a-col :md="5" :sm="24">
              <a-form-item label="手机号">
                <a-input placeholder="请输入手机号" v-model="queryParam.mobile"/>
              </a-form-item>
            </a-col> -->
            <a-col :md="!advanced && 4 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-action:addUserbtn2>新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        :rowKey="(record,index)=>{return index}"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="avatar" slot-scope="text, record">
          <a-avatar :src="record.avatar" :size="54"/>
        </span>

        <span slot="statusname" slot-scope="text, record">
          <a-badge status="success" v-show="record.status == 1" />
          <a-badge status="error" v-show="record.status == 2" />
          <span>{{record.statusname}}</span>
        </span>

        <span slot="rolename" slot-scope="text, record">
          <a-tag color="purple" v-if="record.rolename == '超级管理员'">
            {{record.rolename}}
          </a-tag>
          <a-tag v-else>
            {{record.rolename}}
          </a-tag>
        </span>
        
        <span slot="status" slot-scope="text, record">
          <a-tag color="purple" v-if="record.status == 1">
            启用
          </a-tag>
          <a-tag v-else>
            禁用
          </a-tag>
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)" v-action:updateUserbtn2>修改</a>
            <!-- <a-divider type="vertical" v-action:updateUserbtn2/>
            <a @click="handleSub(record)" v-action:updateUserbtn2>修改密码</a> -->
            
            <a-divider type="vertical" v-action:deleteUserbtn2 v-if="record.rolename!='超级管理员'"/>
            <a v-action:deleteUserbtn2 v-if="record.rolename!='超级管理员'" @click="deleteUserBtn(record)">删除</a>
            <!-- <a-popconfirm
              v-action:deleteUserbtn2
              title="确定删除这个用户吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirm(record)"
              @cancel="cancel(record)"
              v-if="record.rolename!='超级管理员'"
            >
            </a-popconfirm> -->
            <a-divider type="vertical" v-action:forbidUserbtn2/>
            <a @click="handleIsOpen(record)" v-action:forbidUserbtn2>启用</a>
            <a-divider type="vertical" v-action:forbidUserbtn2/>
            <a @click="handleIsOpen(record)" v-action:forbidUserbtn2>禁用</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :isEditSupplier="isEditSupplier"
        @cancel="handleCancel"
        @ok="handleOk"
        showPagination="auto"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { getUserList, AddUser, UpdateUser, DelUser } from '@/api/system'
//引入供应商模块的接口
import supplierApi from '@/api/supplier.js'
// import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'

const columns = [
  {
    title: '编号',
    scopedSlots: { customRender: 'serial' }
  },
  {
   title:'真实姓名',
   dataIndex:'nickname'
  },
  {
    title: '用户名',
    dataIndex: 'username'
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
  },
  {
    title: '角色名称',
    dataIndex: 'rolename',
    scopedSlots: { customRender: 'rolename' }
  },
  {
    title: '禁启用',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '250px',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    STable,
    CreateForm,
  },
  data () {
    this.columns = columns
    return {
      userList:[],
      // campus
      campus_id: 0,
      // 角色
      roleList: [],
      // 部门
      depList: [],
      userShow: false,
      // 图片
      imgUrl: '',
      // updata model
      updata: false,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getUserList(requestParameters).then(res => {
          return res.data
        })
      },
      gys_role_id:'',//供应商角色ID
      supplier_id:'',//供应商表里的ID
      isEditSupplier:false,//是否在编辑供应商
    }
  },
  computed: {
  },
  created() {
    
  },
  methods: {
    // 启用 禁用
    handleIsOpen(record) {
      const value = {id: record.id, status:record.status==1?2:1,role_type:record.type}
      UpdateUser(value).then(res => {
        // 刷新表格
        this.$refs.table.refresh()
      
        this.$message.success('操作成功')
      })
    },
    // 用户图片
    getImage(newValue) {
      this.imgUrl = newValue
      console.log('dddddddddd', this.imgUrl)
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    getSupplierListByMobile(mobile) {
      const params = {
        mobile
      }
      supplierApi.SupplierPage(params)
      .then(res => {
        const supplierList = res.data.data
        console.log('supplierList[0].id',supplierList[0].id)
        this.supplier_id = supplierList[0].id
      })
    },
    handleEdit (record) {
      console.log('record',record)
      if(record.role_id == localStorage.getItem('gys_role_id')) {
        this.isEditSupplier = true
        this.$forceUpdate()
        this.getSupplierListByMobile(record.mobile)
      }else{
        this.isEditSupplier = false
      }
      this.visible = true
      this.mdl = { ...record }
    },
    // 修改密码
    handleUpdataCancel() {
      this.updata = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleUpdataOk() {
      const form = this.$refs.createModal.form
      form.validateFields((error, values) => {
        if(!error) {
          this.confirmLoading = true
          if (values.description === values.password) {
            const value = {id: values.id, password: values.password}
            UpdateUser(value).then(res => {
              this.updata = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('密码修改成功')
            })
          } else {
            this.$message.info('请确认密码保持一致')
            this.confirmLoading = false
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    // 创建
    handleOk () {
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          this.confirmLoading = true
          console.log('values', values)
          const gysRoleId = localStorage.getItem('gys_role_id')
          if(gysRoleId&&values.supplier_id==gysRoleId){
            this.$message.info('供应商请在外部菜单的供应商管理中添加')
            return
          }
          if (values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              // 修改供应商表的信息
              if(this.isEditSupplier){
                const params = {
                  id: this.supplier_id,
                  contacts: values.nickname,
                  mobile:values.mobile
                }
                supplierApi.SupplierSave(params).then(value => {
                  
                })
              }
              // 修改用户表的信息
              UpdateUser(values).then(res => {
                if( res ) {
                  resolve()
                } else {
                  this.confirmLoading = false
                }
              })
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('修改成功')
            })
          } else {
            // 新增
            new Promise((resolve, reject) => {
              AddUser(values).then(res => {
                if( res ) {
                  resolve()
                } else {
                  this.confirmLoading = false
                }
              })
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('新增成功')
            }).catch(error => {
              this.$message.info('该用户名已存在')
              this.confirmLoading = false
            })
          }
        } else {
          console.log(errors)
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    // 显示修改密码窗口
    handleSub (record) {
      this.updata = true
      this.mdl = {...record}
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    deleteUserBtn(record) {
      const _this = this
      this.getSupplierListByMobile(record.mobile)
      this.$confirm({
        title: '系统提示',
        content: '确定删除这个用户吗?',
        onOk () {
          _this.confirm(record)
        },
        onCancel () {}
      })
    },
    // 删除用户信息
    confirm(e) {
      const form = this.$refs.createModal.form
      console.log(e);
      DelUser({id: e.id}).then(res => {
        // 重置表单数据
        form.resetFields()
        // 刷新表格
        this.$refs.table.refresh()
        this.$message.success('删除成功');
      }).catch(error => {
        console.log('-------------error------------', error)
      })
      if(this.supplier_id){
        supplierApi.SupplierDel({
          id: this.supplier_id
        }).then(res => {
          
        })
      }
    },
    cancel(e) {
      console.log(e);
      this.$message.error('已取消');
    },
    // 重置
    reset () {
      // const form = this.$refs.createModal.form
      this.queryParam = {}
        // 重置表单数据
      // form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
  }
  
}
</script>
